﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using ZedGraph;
using ZL.TushareClient.Core;

namespace MyStock
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            industryComboBox.SelectedIndex = 0; // 默认选择第一个
            startDatePicker.Value = DateTime.Now.AddDays(-7); // 默认开始日期为近七天
            endDatePicker.Value = DateTime.Now; // 默认结束日期为今天
            CustomizeUI();
            QueryData();
        }

        private void CustomizeUI()
        {
            // 设置背景颜色
            this.BackColor = ColorTranslator.FromHtml("#f0f0f0");

            // 设置DataGridView样式
            newsDataGridView.BackgroundColor = ColorTranslator.FromHtml("#ffffff");
            newsDataGridView.DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#ffffff");
            newsDataGridView.DefaultCellStyle.ForeColor = ColorTranslator.FromHtml("#000000");
            newsDataGridView.DefaultCellStyle.SelectionBackColor = ColorTranslator.FromHtml("#ffd693");
            newsDataGridView.DefaultCellStyle.SelectionForeColor = ColorTranslator.FromHtml("#000000");
            newsDataGridView.ColumnHeadersDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#ffd693");
            newsDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = ColorTranslator.FromHtml("#000000");
            newsDataGridView.EnableHeadersVisualStyles = false;

            // 设置TextBox样式
            klineTextBox.BackColor = ColorTranslator.FromHtml("#ffffff");
            klineTextBox.ForeColor = ColorTranslator.FromHtml("#000000");
            newsTextBox.BackColor = ColorTranslator.FromHtml("#ffffff");
            newsTextBox.ForeColor = ColorTranslator.FromHtml("#000000");
        }

        private async void IndustryComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            await QueryData();
        }

        private async void QueryButton_Click(object sender, EventArgs e)
        {
            await QueryData();
        }

        private async Task QueryData()
        {
            string industry = industryComboBox.SelectedItem.ToString();
            string startDate = startDatePicker.Value.ToString("yyyyMMdd");
            string endDate = endDatePicker.Value.ToString("yyyyMMdd");
            var stockData = await GetStockData(industry, startDate, endDate);
            DrawKLineChart(stockData);
            var newsData = await GetNewsData(industry);
            DisplayNews(newsData);
        }

        private async Task<List<CandleData>> GetStockData(string industry, string startDate, string endDate)
        {
            string token = "284b804f2f919ea85cb7e6dfe617ff81f123c80b4cd3c4b13b35d736"; // 替换为你的Tushare API token
            var client = new TuShareClient(token);

            var dt = await client.CallApiDataTable("sw_daily",
                new Dictionary<string, string>() { { "ts_code", industry == "汽车" ? "801880.SI" : "801740.SI" }, { "start_date", startDate }, { "end_date", endDate } },
                new List<string>() { "trade_date", "open", "high", "low", "close" });

            var data = new List<CandleData>();
            foreach (DataRow item in dt.Rows)
            {
                var cc = new CandleData
                {
                    Date = DateTime.ParseExact(item["trade_date"].ToString(), "yyyyMMdd", null),
                    Open = Convert.ToDouble(item["open"]),
                    High = Convert.ToDouble(item["high"]),
                    Low = Convert.ToDouble(item["low"]),
                    Close = Convert.ToDouble(item["close"])
                };
                data.Add(cc);
            }

            return data;
        }

        private void DrawKLineChart(List<CandleData> data)
        {
            GraphPane pane = zedGraphControl.GraphPane;
            pane.CurveList.Clear();
            pane.Title.Text = "K线图";
            pane.XAxis.Title.Text = "日期";
            pane.XAxis.Title.FontSpec.FontColor = Color.Black;
            pane.YAxis.Title.Text = "价格";
            pane.YAxis.Title.FontSpec.FontColor = Color.Black;

            // 设置背景颜色
            Color c1 = ColorTranslator.FromHtml("#ffffff");
            Color c2 = ColorTranslator.FromHtml("#ffd693");
            pane.Chart.Fill = new Fill(c1); // 图形区域颜色
            pane.Fill = new Fill(c2); // 整体颜色

            // 设置网格线颜色
            pane.XAxis.MajorGrid.IsVisible = true;
            pane.XAxis.MajorGrid.Color = Color.LightGray;
            pane.YAxis.MajorGrid.IsVisible = true;
            pane.YAxis.MajorGrid.Color = Color.LightGray;

            // 设置日期格式
            pane.XAxis.Type = AxisType.Date;
            pane.XAxis.Scale.Format = "yyyy-MM-dd";
            pane.XAxis.Scale.MajorUnit = DateUnit.Day;
            pane.XAxis.Scale.MajorStep = 1;
            pane.XAxis.Scale.FontSpec.Angle = 45; // X轴文字方向，0-90度
            pane.XAxis.Scale.FontSpec.FontColor = Color.Black;
            pane.YAxis.Scale.FontSpec.FontColor = Color.Black;

            // 设置K线图的颜色和样式
            StockPointList stockPointList = new StockPointList();
            foreach (var item in data)
            {
                stockPointList.Add(new XDate(item.Date), item.High, item.Low, item.Open, item.Close, 0); // 添加vol参数
            }

            JapaneseCandleStickItem myCurve = pane.AddJapaneseCandleStick("K线图", stockPointList);
            myCurve.Stick.IsAutoSize = true;
            myCurve.Stick.FallingFill = new Fill(Color.Green); // 下跌填充色
            myCurve.Stick.RisingFill = new Fill(Color.Red); // 上涨填充色
            myCurve.Stick.FallingBorder = new Border(Color.Green, 1); // 下跌边框和上下影线的颜色
            myCurve.Stick.RisingBorder = new Border(Color.Red, 1); // 上涨边框和上下影线的颜色

            // 设置图表的边框颜色
            pane.Border.Color = Color.Black;

            zedGraphControl.AxisChange();
            zedGraphControl.Invalidate();
        }

        private async Task<List<NewsData>> GetNewsData(string industry)
        {
            string apiUrl = "http://v.juhe.cn/toutiao/index";
            string apiKey = "d72af816907302734330465c61bcd49b"; // 聚合数据API key
            string type = industry == "汽车" ? "qiche" : "junshi";

            using (HttpClient client = new HttpClient())
            {
                var response = await client.GetStringAsync($"{apiUrl}?type={type}&key={apiKey}");
                var jsonResponse = JObject.Parse(response);

                var data = new List<NewsData>();
                foreach (var item in jsonResponse["result"]["data"])
                {
                    data.Add(new NewsData
                    {
                        新闻标题 = item["title"].ToString(),
                        地址 = item["url"].ToString()
                    });
                }

                return data;
            }
        }

        private void DisplayNews(List<NewsData> newsData)
        {
            newsDataGridView.DataSource = newsData;
            newsDataGridView.Columns["地址"].Visible = false;
        }

        private void NewsDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var url = newsDataGridView.Rows[e.RowIndex].Cells["地址"].Value.ToString();
                System.Diagnostics.Process.Start(url);
            }
        }
    }

    public class CandleData
    {
        public DateTime Date { get; set; }
        public double Open { get; set; }
        public double High { get; set; }
        public double Low { get; set; }
        public double Close { get; set; }
    }

    public class NewsData
    {
        public string 新闻标题 { get; set; }
        public string 地址 { get; set; }
    }
}
